package cn.lsnu.common.interceptor;

import cn.lsnu.common.sys.entity.MenuEntity;
import cn.lsnu.common.sys.service.MenuService;
import cn.lsnu.modules.oa.entity.RoleEntity;
import cn.lsnu.modules.oa.service.RoleService;
import cn.lsnu.utils.Global;
import org.apache.commons.collections.bag.SynchronizedSortedBag;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;
import java.util.List;

/**
 * @Description    
 * @param null: 
 * @return null 
 * @author  lin 
 * @Datetime  2020/4/8 20:33
 */  
public class LoginInterceptor implements HandlerInterceptor {

    private List<String> passList;
    @Autowired
    private MenuService menuService;
    @Autowired
    private RoleService roleService;
    private static Logger logger = LoggerFactory.getLogger(LoginInterceptor.class);
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {

        HttpSession session = request.getSession();
        String sesssionId = (String) session.getAttribute(Global.SESSION_ID);
        String type = request.getHeader("X-Requested-With");// XMLHttpRequest
        String urlStr = request.getRequestURI();
        String urlPath = request.getServletPath();
        String urlParam= request.getQueryString();
        String urlStrs[] = urlStr.split("/");
        //app请求直接放行
        for(String str:urlStrs){
            if(str.equalsIgnoreCase("app")){
                return true;
            };
        }
        System.out.println(urlPath);

        //放行的url
        if(passList != null && passList.size() != 0){
            for(String str : passList){
                if(urlStr.equals("/login/weblogin/users")){
                    return true;
                }
            }
        }
        if(sesssionId == null){
            //如果是ajax请求响应头会有x-requested-with
            if (request.getHeader("x-requested-with") != null && StringUtils.equals("XMLHttpRequest", type)){
//                ServletOutputStream out = response.getOutputStream();
                PrintWriter out = response.getWriter();
                response.setHeader("SESSIONSTATUS", "TIMEOUT");
                response.setHeader("CONTEXTPATH", request.getContextPath()+"/webpage/common/login/login.jsp");
                // FORBIDDEN，forbidden。403
                response.setStatus(HttpServletResponse.SC_FORBIDDEN);
                out.flush();
                out.close();
                return false;
            }else {
//                request.getRequestDispatcher(request.getContextPath() + "/webpage/common/login/login.jsp").forward(request, response);
                response.getWriter().print("<script type=\"text/javascript\">"+"window.parent.location.href="+request.getContextPath()+"'/webpage/common/login/login.jsp'"+";</script>");
                logger.error(request.getContextPath() + "/webpage/common/login/login.jsp");
                return false;
            }
        }
        logger.error("SESSION:"+session.getAttribute(Global.SESSION_ID));
        logger.debug("preHandle执行");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object o, ModelAndView modelAndView) throws Exception {

        HttpSession session = request.getSession();
        String userCode  = (String) session.getAttribute(Global.SESSION_ID);
        MenuEntity menuEntity = new MenuEntity();
        menuEntity.setUserCode(userCode);
        try {
            List<MenuEntity> menuLists = menuService.findLoginMenu(menuEntity);
            List<MenuEntity> allMenuLists = menuService.findList(null);
            List<RoleEntity> roleLists = roleService.findList(null);
            session.setAttribute("menus",menuLists);
            session.setAttribute("allMenus",allMenuLists);
            session.setAttribute("roles",roleLists);
        }catch (Exception e){
                e.printStackTrace();
        }
        logger.debug("postHandle执行");
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        logger.debug("afterCompletion执行");
    }


    public List<String> getPassList() {
        return passList;
    }

    public void setPassList(List<String> passList) {
        this.passList = passList;
    }
}
